package com.learn.framework.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@RestController
public class DemoController {
    /**
     * 功能：请求测试
     *
     * @param name
     * @return
     * @author wsh
     * @date 2020/10/9
     */
    @RequestMapping("/return/{name}")
    public String greeting(@PathVariable("name") String name) {
        // 如果这样直接返回就是一个新的页面流，而且没有指定页面编码，会默认使用 ISO-8859-1，带来 response 乱码（无法正常显示中文，即使增加 RequestFilter 过滤器也不行）
        return "hello, " + name;
    }

    @RequestMapping("/{name}")
    public void greeting2(@PathVariable("name") String name, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        String result = "hello, " + name;

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(result);
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}
